package com.yangcangclub.commons.velocity;

import com.yangcangclub.commons.utils.ClassUtils;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.charset.Charset;

/**
 *
 * ext21模板资源提供者(读取vm文件)
 *
 */
@Component
public class TemplateProvider implements IVMTemplateProvider {

    /*提供者名称*/
    public static final String PROVIDER_NAME = "EXT21_VM_RESOURCE";

    /*资源文件vm所在位置 (具体位置待修改)*/
    public static final String[] VM_PATHS = {"vm/"};

    /**
     * 取得默认的字符集
     * @return
     */
    public Charset defaultCharset() {
        return Charset.forName("UTF-8");
    }

    /**
     * 取得模板的版本号
     * @param name
     * @return
     */
    public long getTplVersion(String name) {
        return 0;
    }

    /**
     * 取得模板提供源(解析VM文件)
     * @param name
     * @return
     */
    public String getVMSource(String name) {
        try {
            InputStream vmPathStream = findVMStream(name);
            InputStreamReader reader = new InputStreamReader(vmPathStream,
                    Charset.forName(this.defaultCharset().name()));
            StringWriter sw = new StringWriter();
            int ch = reader.read();
            while (ch != -1) {
                sw.write(ch);
                ch = reader.read();
            }
            String vmContent = sw.toString();
            reader.close();
            sw.close();
            return vmContent;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 转为流
     * @param name
     * @return
     */
    private InputStream findVMStream(String name) {
        InputStream inStream = null;
        for (String vmpath : VM_PATHS) {
            String path = vmpath + name;
            inStream = ClassUtils.getClassPathRes(path);
            if (inStream != null) {
                return inStream;
            }
        }
        return inStream;
    }

    /**
     * 当前提供源是否需要缓存
     * @return
     */
    public boolean isCachingOn() {
        return false;
    }

    /**
     * 取得模板提供者名称
     * @return
     */
    public String providerName() {
        return PROVIDER_NAME;
    }

}
